package cn.findviewbydream.evil.main.service.impl;

import cn.findviewbydream.evil.main.dao.LoginDao;
import cn.findviewbydream.evil.main.entity.UserEntity;
import cn.findviewbydream.evil.main.enums.LoginType;
import cn.findviewbydream.evil.main.enums.RegisterType;
import cn.findviewbydream.evil.main.service.LoginService;
import cn.findviewbydream.evil.main.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

/********************************************
 * 工程名：HebeuCS
 * 包名：cn.findviewbydream.evil.main.service.impl
 * 时间：16-11-1 下午5:40
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：注册实现类
 ********************************************/
@Service("registerService")
public class LoginServiceImpl implements LoginService
{
    private Logger logger = LoggerFactory.getLogger(ReleaseNewpostServiceImpl.class);

    private final LoginDao loginDao;

    private static final String salt = "@$^&$GDD^^%#$@TRU#$@$YCD";

    @Autowired
    public LoginServiceImpl(LoginDao loginDao)
    {
        this.loginDao = loginDao;
    }

    @Override
    public LoginType login(HttpSession session, String userName, String userPassword)
    {
        userName = userName.trim();
        userPassword = userPassword.trim();

        String passwordMd5 = MD5Util.get(userPassword + salt);

        UserEntity entity = new UserEntity();
        entity.setUserName(userName);
        try
        {
            UserEntity userEntity = loginDao.selectUser(entity);
            if (userEntity != null)
            {
                /*验证是否为黑名单*/
                if (!selectBlack(userName))
                {
                    /*验证密码*/
                    if (userEntity.getUserPassword().equals(passwordMd5))
                    {
                        /*更新最后一次登录时间->如果返回为0,则发生错误,阻止登录*/
                        if (loginDao.updateLastloginTime(userEntity.getUserName()) == 0)
                            return LoginType.ERROR;

                        /*判读是否为管理员*/
                        if (userName.contains("admin:"))
                        {
                            session.setAttribute("admin", userEntity);
                            session.setAttribute("user", userEntity);
                            return LoginType.ADMIN;
                        }
                        else
                        {
                            session.setAttribute("user", userEntity);
                            return LoginType.SUCCESS;
                        }
                    }
                    else
                        return LoginType.FAIL_PASSWORD_ERROR;
                }
                else
                    return LoginType.INBLACK;
            }
            else
                return LoginType.FAIL_NULL;
        }
        catch (DataAccessException e)
        {
            logger.error(e.toString());
            return LoginType.ERROR;
        }
    }

    @Override
    public boolean exit(HttpSession session)
    {
        if (session.getAttribute("user") != null)
        {
            session.removeAttribute("user");
            if (session.getAttribute("admin") != null)
            {
                session.removeAttribute("admin");
                return true;
            }
            return true;
        }
        else
            return false;
    }

    @Override
    public String setCookie(String userName, String userPassword, boolean remember)
    {
        if (remember)
            return "|" + userName + "|" + MD5Util.get(userPassword + salt);
        else
            return "";
    }

    @Override
    public boolean getCookie(HttpSession session, Cookie[] cookies)
    {
        String userName = null, userPassword = null;
        if (cookies != null && cookies.length > 0)
        {
            for (Cookie cookie : cookies)
            {
                if (cookie.getName().equals("ue"))
                    userName = cookie.getValue();

                if (cookie.getName().equals("up"))
                    userPassword = cookie.getValue();
            }
            if (userName != null && userPassword != null)
            {
                UserEntity entity = new UserEntity();
                entity.setUserName(userName);
                try
                {
                    UserEntity userEntity = loginDao.selectUser(entity);
                    if (userEntity != null)
                        if (userEntity.getUserPassword().equals(userPassword))
                        {
                            if (userName.contains("admin:"))
                                session.setAttribute("admin", userEntity);

                            session.setAttribute("user", userEntity);
                            return true;
                        }
                }
                catch (DataAccessException e)
                {
                    logger.error(e.toString());
                    return false;
                }
            }
        }
        return false;
    }

    @Override
    public RegisterType register(String userName, String userPassword, String userRealName)
    {
        /*管理员标识,不允许注册->防止绕过前端验证*/
        if (userName.contains(":"))
            return RegisterType.FAIL_REPEAT;
        try
        {
            int re = loginDao.insertUser(new UserEntity(userName.trim(), MD5Util.get(userPassword.trim() + salt),
                    userRealName.trim()));
            if (re == 1)
                return RegisterType.SUCCESS;
            else
                return RegisterType.ERROR;
        }
        catch (DataAccessException e)
        {
            if (e.toString().contains("Duplicate entry '" + userName + "' for key 'PRIMARY'"))
                return RegisterType.FAIL_REPEAT;
            else if (e.toString().contains("Data too long"))
                return RegisterType.FAIL_TOLONG;
            else
            {
                logger.error(e.toString());
                return RegisterType.ERROR;
            }
        }
    }

    @Override
    public boolean selectBlack(String userName)
    {
        if (loginDao.selectBlack(userName) != null)
            return loginDao.selectBlack(userName);
        else
            return false;
    }

    @Override
    public boolean updateBlack(String userName, boolean isBlack)
    {
        return loginDao.updateBlack(userName, isBlack) > 0;
    }
}
